package club.monkeywood.service.buyer.impl;

import club.monkeywood.dataobject.Buyer;
import club.monkeywood.dataobject.OrderDetail;
import club.monkeywood.dataobject.OrderMaster;
import club.monkeywood.dataobject.Production;
import club.monkeywood.enums.ResponseEnum;
import club.monkeywood.enums.order.OrderStatusEnum;
import club.monkeywood.enums.order.PayStatusEnum;
import club.monkeywood.exception.SellException;
import club.monkeywood.repository.BuyerRepository;
import club.monkeywood.repository.OrderMasterRepository;
import club.monkeywood.repository.ProductionInfoRepository;
import club.monkeywood.request.buyer.OrderRequest;
import club.monkeywood.request.buyer.SelectedProductionRequest;
import club.monkeywood.service.buyer.OrderDetailService;
import club.monkeywood.service.buyer.OrderMasterService;
import club.monkeywood.service.buyer.ProductionInfoService;
import club.monkeywood.util.key.KeyUtil;
import club.monkeywood.vo.buyer.OrderDetailVO;
import club.monkeywood.vo.buyer.OrderMasterVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderMasterServiceImpl implements OrderMasterService {

    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ProductionInfoService productionInfoService;

    @Autowired
    private BuyerRepository buyerRepository;

    @Override
    public OrderMaster save(OrderMaster orderMaster) {
        return orderMasterRepository.save(orderMaster);
    }

    @Override
    public OrderMasterVO createOrder(OrderRequest orderRequest) {

        //1.订单数据存db
        //订单id
        String orderId = KeyUtil.genUniqueKey();
        //总价
        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);

        //2.遍历订单明细表，取出单价和数量，保存入库
        List<OrderDetailVO> orderDetailVOList = new ArrayList<>();
        for (SelectedProductionRequest productionRequest: orderRequest.getProductions()) {
            //1)查询商品（数量，价格）
            Production production = productionInfoService.findById(productionRequest.getId());
            //2)冗错：
            //商品不存在，抛异常，在全局异常处理器处返回错误码及错误描述
            if (production == null) {
                throw new SellException(ResponseEnum.PRODUCT_NOT_EXIST);
            }

            //3)累加得总价
            orderAmount = production.getPrice()
                    .multiply(new BigDecimal(productionRequest.getCount()))
                    .add(orderAmount);

            //4)订单详情入库
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setId(KeyUtil.genUniqueKey());
            orderDetail.setOrderId(orderId);
            orderDetail.setProductId(productionRequest.getId());
            orderDetail.setProductName(production.getName());
            orderDetail.setProductPrice(production.getPrice());
            orderDetail.setProductQuantity(productionRequest.getCount());
            orderDetail = orderDetailService.save(orderDetail);

            //5)生成返回订单明细对象列表
            OrderDetailVO orderDetailVO = new OrderDetailVO();
            BeanUtils.copyProperties(orderDetail,orderDetailVO);
            orderDetailVOList.add(orderDetailVO);

            //6)扣除库存
            productionInfoService.decreaseStock(orderDetail.getProductId(),productionRequest.getCount());

        }

        //3.订单主数据入库
        OrderMaster orderMaster = new OrderMaster();
        orderMaster.setId(orderId);

        Buyer buyer = buyerRepository.findByOpenid(orderRequest.getOpenid());
        orderMaster.setBuyerId(buyer.getId());

        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        orderMaster = orderMasterRepository.save(orderMaster);

        //4.拼装返回订单对象
        OrderMasterVO orderMasterVO = new OrderMasterVO();
        BeanUtils.copyProperties(orderMaster,orderMasterVO);
        orderMasterVO.setProductions(orderDetailVOList);

        ////发送webSocket消息
        //webSocket.sendMessage("有新的订单");

        return orderMasterVO;
    }

}
